<template>
  <div class="answer-card" :id="`answer-${answer.id}`">
    <!-- 回答头部 -->
    <div class="answer-header">
      <div class="author-info" @click="goToProfile">
        <el-avatar
          :size="32"
          :src="getMediaUrl(answer.author?.avatar)"
          class="author-avatar"
        >
          {{ answer.author?.nickname?.charAt(0) || answer.author?.username?.charAt(0) }}
        </el-avatar>
        <div class="author-details">
          <div class="author-name">
            {{ answer.author?.nickname || answer.author?.username }}
            <el-tag v-if="answer.isBest" type="warning" size="small" class="best-tag">
              best answer
            </el-tag>
            <el-tag v-if="isQuestionAuthor" type="success" size="small" class="author-tag">
              Title Owner
            </el-tag>
          </div>
          <div class="publish-info">
            <span class="publish-time">{{ formatTime(answer.createdTime) }}</span>
            <span v-if="answer.updatedTime !== answer.createdTime" class="edit-time">
              · Edited on {{ formatTime(answer.updatedTime) }}
            </span>
          </div>
        </div>
      </div>
      
      <div class="answer-actions">
        <el-dropdown trigger="click" v-if="canOperate">
          <el-button type="text" class="more-btn">
            <el-icon><MoreFilled /></el-icon>
          </el-button>
          <template #dropdown>
            <el-dropdown-menu>
              <el-dropdown-item v-if="canEdit" @click="handleEdit">
                <el-icon><Edit /></el-icon>
                Edit
              </el-dropdown-item>
              <el-dropdown-item v-if="canDelete" @click="handleDelete">
                <el-icon><Delete /></el-icon>
                Delete
              </el-dropdown-item>
              <el-dropdown-item v-if="canSetBest" @click="handleSetBest">
                <el-icon><Star /></el-icon>
                Star
              </el-dropdown-item>
              <el-dropdown-item @click="handleReport">
                <el-icon><Warning /></el-icon>
                Report
              </el-dropdown-item>
            </el-dropdown-menu>
          </template>
        </el-dropdown>
      </div>
    </div>

    <!-- 回答内容 -->
    <div class="answer-content">
      <div class="answer-text" v-html="answer.content"></div>
    </div>

    <!-- 回答操作栏 -->
    <div class="answer-footer">
      <div class="answer-stats">
        <span class="stat-item">
          <el-icon><View /></el-icon>
          reading
        </span>
        <span class="stat-item">
          <el-icon><ChatDotRound /></el-icon>
          {{ formatCount(answer.commentCount) }} comment
        </span>
      </div>

      <div class="answer-operations">
        <!-- 点赞按钮 -->
        <button 
          class="operation-btn"
          :class="{ active: answer.isLiked }"
          @click="handleLike"
        >
          <el-icon><CaretTop /></el-icon>
          <span>{{ formatCount(answer.likeCount) }}</span>
        </button>

        <!-- 踩按钮 -->
        <button 
          class="operation-btn"
          :class="{ active: answer.isDisliked }"
          @click="handleDislike"
        >
          <el-icon><CaretBottom /></el-icon>
          <span>{{ formatCount(answer.dislikeCount) }}</span>
        </button>

        <!-- 评论按钮 -->
        <button
          class="operation-btn"
          :class="{ active: showComments }"
          @click="handleComment"
        >
          <el-icon><ChatDotRound /></el-icon>
          <span>comment</span>
        </button>

        <!-- 分享按钮 -->
        <button 
          class="operation-btn"
          @click="handleShare"
        >
          <el-icon><Share /></el-icon>
          <span>share</span>
        </button>
      </div>
    </div>

    <!-- 评论区域 -->
    <div v-if="showComments" class="comments-section">
      <CommentList
        :target-id="answer.id"
        :target-type="2"
      />
    </div>
  </div>
</template>

<script setup>
import {computed, ref} from 'vue'
import {useRouter} from 'vue-router'
import {ElMessage, ElMessageBox} from 'element-plus'
import {useUserStore} from '@/stores/user'
import {formatCount, formatTime} from '@/utils/format'
import {getMediaUrl} from '@/utils/media'
import CommentList from './CommentList.vue'

const router = useRouter()
const userStore = useUserStore()

// 响应式数据
const showComments = ref(false)

// Props
const props = defineProps({
  answer: {
    type: Object,
    required: true
  },
  questionAuthorId: {
    type: String,
    default: ''
  }
})

// Emits
const emit = defineEmits(['like', 'dislike', 'delete', 'edit', 'set-best', 'comment'])

// 计算属性
const currentUserId = computed(() => userStore.userInfo?.userId)

const isQuestionAuthor = computed(() => {
  return props.answer.author?.userId === props.questionAuthorId
})

const canEdit = computed(() => {
  return currentUserId.value === props.answer.author?.userId
})

const canDelete = computed(() => {
  return currentUserId.value === props.answer.author?.userId || 
         currentUserId.value === props.questionAuthorId
})

const canSetBest = computed(() => {
  return currentUserId.value === props.questionAuthorId && !props.answer.isBest
})

const canOperate = computed(() => {
  return canEdit.value || canDelete.value || canSetBest.value
})

// 跳转到作者主页
const goToProfile = () => {
  if (props.answer.author?.userId) {
    router.push(`/people/${props.answer.author.userId}`)
  }
}

// 处理点赞
const handleLike = async () => {
  if (!currentUserId.value) {
    ElMessage.warning('请先登录')
    return
  }
  emit('like', props.answer.id, props.answer.isLiked)
}

// 处理踩
const handleDislike = async () => {
  if (!currentUserId.value) {
    ElMessage.warning('请先登录')
    return
  }
  emit('dislike', props.answer.id, props.answer.isDisliked)
}

// 处理编辑
const handleEdit = () => {
  emit('edit', props.answer.id)
}

// 处理删除
const handleDelete = async () => {
  try {
    await ElMessageBox.confirm('确定要删除这个回答吗？', '提示', {
      confirmButtonText: '确定',
      cancelButtonText: '取消',
      type: 'warning'
    })
    emit('delete', props.answer.id)
  } catch (error) {
    // 用户取消删除
  }
}

// 设置最佳答案
const handleSetBest = () => {
  emit('set-best', props.answer.id)
}

// 处理评论
const handleComment = () => {
  showComments.value = !showComments.value
  emit('comment', props.answer.id)
}

// 处理分享
const handleShare = () => {
  ElMessage.success('分享链接已复制到剪贴板')
}

// 处理举报
const handleReport = () => {
  ElMessage.info('举报功能开发中')
}
</script>

<style lang="scss" scoped>
.answer-card {
  background: white;
  border-radius: 8px;
  padding: 20px;
  margin-bottom: 16px;
  border: 1px solid #f0f0f0;
  transition: box-shadow 0.2s;

  &:hover {
    box-shadow: 0 2px 8px rgba(0, 0, 0, 0.1);
  }
}

.answer-header {
  display: flex;
  justify-content: space-between;
  align-items: flex-start;
  margin-bottom: 16px;
}

.author-info {
  display: flex;
  align-items: center;
  gap: 12px;
  cursor: pointer;
  
  &:hover .author-name {
    color: #b92b27;
  }
}

.author-details {
  .author-name {
    display: flex;
    align-items: center;
    gap: 8px;
    font-weight: 500;
    color: #1a1a1a;
    margin-bottom: 4px;
    transition: color 0.2s;
    
    .best-tag {
      font-size: 12px;
    }
    
    .author-tag {
      font-size: 12px;
    }
  }
  
  .publish-info {
    font-size: 13px;
    color: #8a8a8a;
    
    .edit-time {
      color: #999;
    }
  }
}

.answer-actions {
  .more-btn {
    color: #8a8a8a;
    
    &:hover {
      color: #b92b27;
    }
  }
}

.answer-content {
  margin-bottom: 20px;
}

.answer-text {
  font-size: 16px;
  line-height: 1.6;
  color: #1a1a1a;
  word-break: break-word;
  
  // 处理富文本内容样式
  :deep(p) {
    margin: 0 0 12px 0;
    
    &:last-child {
      margin-bottom: 0;
    }
  }
  
  :deep(img) {
    max-width: 100%;
    height: auto;
    border-radius: 4px;
  }
}

.answer-footer {
  display: flex;
  justify-content: space-between;
  align-items: center;
  padding-top: 16px;
  border-top: 1px solid #f0f0f0;
}

.answer-stats {
  display: flex;
  gap: 20px;
  
  .stat-item {
    display: flex;
    align-items: center;
    gap: 4px;
    font-size: 14px;
    color: #8a8a8a;
  }
}

.answer-operations {
  display: flex;
  gap: 8px;
  
  .operation-btn {
    display: flex;
    align-items: center;
    gap: 4px;
    padding: 6px 12px;
    border: 1px solid #e1e1e1;
    border-radius: 4px;
    background: white;
    color: #8a8a8a;
    font-size: 13px;
    cursor: pointer;
    transition: all 0.2s;
    
    &:hover {
      border-color: #b92b27;
      color: #b92b27;
    }
    
    &.active {
      border-color: #b92b27;
      color: #b92b27;
      background: #f0f8ff;
    }
  }
}

.comments-section {
  margin-top: 16px;
  padding-top: 16px;
  border-top: 1px solid #f0f0f0;
}
</style>
